<template>
  <div class="main-layout">
    <el-card class="box-card-list" shadow="never" v-loading="loading">
      <div class="text-large-up-26">
        文章列表
      </div>
      <!-- 头部推荐文章 -->
      <div class="rotationPic" v-if="recommendArticles.length > 0">
        <div class="rotationPic-item list-select" 
          v-for="(item, index) in recommendArticles" 
          :key="item.article_id"
          @click="goDetails(item.article_id)"
        >
          <img 
            :src="getImageByIndex(index)" 
            :alt="item.title"
            @error="handleImageError"
          >
          <div class="rotationPic-item-title">
            {{ item.title }}
          </div>
        </div>
      </div>

      <!-- 文章列表 -->
      <div class="content-list">
        <!-- 添加调试信息 -->
        <div v-if="articleList.length === 0">暂无文章</div>
        
        <div :class="{
          'list-item': true,
          'margin-space': true,
          'list-height': true,
          'list-select': true,
          'odd-item': judgeOdd(index),
          'even-item': judgeEven(index),
        }" v-for="(item, index) in articleList" 
           :key="item.article_id" 
           @click="goDetails(item.article_id)"
        >
          <div class="text-large">{{ item.title }}</div>
          <div class="text-large">{{ formatDate(item.publish_time) }}</div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="example-pagination-block" v-if="total > 0">
        <el-pagination 
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import ArticleApi from '@/api/article'
import type { ArticleData } from '@/api/article/types'
import { ElMessage } from 'element-plus'
import pic1 from "@/assets/images/article1.png"
import pic2 from "@/assets/images/article2.png"
import pic3 from "@/assets/images/rotationpic2.png"

const router = useRouter()
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const articleList = ref<ArticleData[]>([])

const recommendArticles = computed(() => {
  if (!articleList.value) return []
  return articleList.value
    .filter(article => article?.is_recommend === 1)
    .slice(0, 3)
})

// 获取文章列表
const getArticleList = async () => {
  try {
    loading.value = true
    const response = await ArticleApi.getArticles({
      Page: currentPage.value,
      Size: pageSize.value,
      is_delete: 0,
      review_status: 1
    })
    
    // 直接使用返回的数组数据
      if (Array.isArray(response.data)) {
        articleList.value = response.data
        total.value = response.data.total  // 或者使用后端返回的总数
      } else {
      articleList.value = []
      total.value = 0
      console.log('Invalid data format')
    }
  } catch (error) {
    ElMessage.error('获取文章列表失败')
    console.error('获取文章列表失败:', error)
    articleList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getArticleList()
}

// 处理每页数量变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getArticleList()
}

// 跳转到详情页
const goDetails = (articleId: number) => {
  router.push({
    name: 'articleDetail',
    params: { id: String(articleId) }
  })
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

const judgeOdd = (index: number) => index % 2 === 0
const judgeEven = (index: number) => index % 2 !== 0

// 根据索引返回对应图片
const getImageByIndex = (index: number) => {
  switch (index) {
    case 0: return pic1
    case 1: return pic2
    case 2: return pic3
    default: return pic1  // 默认返回 pic1
  }
}

// 图片加载错误处理
const handleImageError = (e: Event) => {
  const img = e.target as HTMLImageElement
  console.error('Image failed to load:', img.src)
  img.src = pic1  // 加载失败时使用 pic1 作为默认图片
}

onMounted(() => {
  getArticleList()
})
</script>

<style scoped>
.main-layout {
  padding: 20px;
}

.content-list {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.list-item {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  border-radius: 4px;
}

.list-height {
  height: 40px;
  line-height: 40px;
}

.list-select {
  cursor: pointer;
}

.list-select:hover {
  background-color: #f5f7fa;
}

.odd-item {
  background-color: #ffffff;
}

.even-item {
  background-color: #f5f7fa;
}

.margin-space {
  margin: 10px 0;
}

.example-pagination-block {
  margin-top: 20px;
  text-align: center;
}

/* 推荐文章样式 */
.rotationPic {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 30px;
}

.rotationPic-item {
  max-width: 350px;
}

.rotationPic-item img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.rotationPic-item-title {
  margin-top: 10px;
  font-size: 16px;
  text-align: center;
}

.example-pagination-block {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.pagination {
  margin: 20px 0;
}
</style>